package com.pe1n.yangtaopai.view.fragment;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.pe1n.yangtaopai.R;
import com.pe1n.yangtaopai.adapter.CarBottomReclerAdapter;
import com.pe1n.yangtaopai.adapter.ShoppingFragmentAdapter;
import com.pe1n.yangtaopai.base.BaseFragment;
import com.pe1n.yangtaopai.bean.BigCarBean;
import com.pe1n.yangtaopai.bean.CarBean;
import com.pe1n.yangtaopai.bean.CarBeanHelper;
import com.pe1n.yangtaopai.bean.CarBottomBean;
import com.pe1n.yangtaopai.helper.InitRetrofitHelper;
import com.pe1n.yangtaopai.helper.IupDataListener;
import com.pe1n.yangtaopai.helper.IupDataListenerTwo;
import com.pe1n.yangtaopai.retrofitApi.RetrofitApi;
import com.pe1n.yangtaopai.utils.URLConstant;
import com.pe1n.yangtaopai.view.activity.Main2Activity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class ShoppingFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private RecyclerView mRecyclerView;//滑动控件
    private ImageView imageView;//选择的按钮
    private TextView mTextViewMoney;//钱
    private TextView mTextViewTrue;//确认付款
    private List<Object> mList;//数据源
    private Context context;
    private SharedPreferences mSharePreferrnces;
    private RetrofitApi retrofitApi;
    private ShoppingFragmentAdapter shoppingFragmentAdapter;
    private String name;
    private TextView mTextView;
    private IupDataListenerTwo iupDataListenerTwo;
    private CarBottomBean carBottomBeanMain;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private double moneyAll;//总价格
    private boolean mBoolean;

    public ShoppingFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ShoppingFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ShoppingFragment newInstance(String param1, String param2) {
        ShoppingFragment fragment = new ShoppingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_shopping, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mList = new ArrayList<>();
        context = getContext();
        mTextView= (TextView) view.findViewById(R.id.fragment_shopping_textView_select);
        iupDataListenerTwo=new IupDataListenerTwo() {
            @Override
            public void upDataTwo(double price, boolean b) {

                if(b){
                    moneyAll+=price;
                    if(price==0.0){
                        moneyAll=0.0;
                    }
                }
                else{
                    moneyAll-=price;
                    if( moneyAll<0.0){
                        moneyAll=0.0;
                    }
                }
                mTextViewMoney.setText("¥"+moneyAll);
            }

            @Override
            public void upDataBmob() {
             getData("userName",name);
            }

            @Override
            public void upCollectData() {

            }

        };
        shoppingFragmentAdapter = new ShoppingFragmentAdapter(context, mList,iupDataListenerTwo );
        mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_shopping_recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
        mRecyclerView.setAdapter(shoppingFragmentAdapter);
        imageView = (ImageView) view.findViewById(R.id.fragment_shopping_imageView_select);
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                  if( !mBoolean){
                      if(!name.equals("no")) {
                          mTextView.setText("全不选");
                          imageView.setImageResource(R.drawable.cart_select);
                          upDataChoice(true, name);
                          mBoolean = true;
                      }
                  }
                else{
                      if(!name.equals("no")){
                          imageView.setImageResource(R.drawable.cart_select_normalx);
                          mTextView.setText("全选");
                          upDataChoice(false, name);
                          mBoolean=false;
                      }
                  }
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if( !mBoolean){
                    if(!name.equals("no")) {
                        mTextView.setText("全不选");
                        imageView.setImageResource(R.drawable.cart_select);
                        upDataChoice(true, name);
                        mBoolean = true;
                    }
                }
                else{
                    if(!name.equals("no")){
                        imageView.setImageResource(R.drawable.cart_select_normalx);
                        mTextView.setText("全选");
                        upDataChoice(false, name);
                        mBoolean=false;
                    }


                }
            }
        });
        mTextViewMoney = (TextView) view.findViewById(R.id.fragment_shopping_textView_all_money);
        mTextViewTrue = (TextView) view.findViewById(R.id.fragment_shopping_textView_text_true);
        initData();
        mTextViewTrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(context, Main2Activity.class);
                context.startActivity(intent);
            }
        });

    }

    private void initData() {
        retrofitApi = InitRetrofitHelper.getRetrofitInterfance();
        retrofitApi.getCarBottomBean(URLConstant.CAR_BOTTOM)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<CarBottomBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(final CarBottomBean carBottomBean) {
                        carBottomBeanMain = carBottomBean;
                        mList.clear();
                        //mList.add(0,new CarBean());
                        final BigCarBean bigCarBean = new BigCarBean();
                        shoppingFragmentAdapter.notifyDataSetChanged();
                        mSharePreferrnces = getContext().getSharedPreferences("myshared", 0);
                        name = mSharePreferrnces.getString("shareUserName", "no");
                        BmobQuery<CarBean> query = new BmobQuery<CarBean>();
                        Log.e("bmob", name);
                        query.addWhereEqualTo("userName", name);
                        query.findObjects(new FindListener<CarBean>() {
                            @Override
                            public void done(List<CarBean> list, BmobException e) {
                                if (e == null) {
                                    bigCarBean.setList(list);
                                    // mList.addAll(0, list);
                                    mList.add(bigCarBean);
                                    mList.add(carBottomBean);
                                    shoppingFragmentAdapter.notifyDataSetChanged();
                                    Log.e("bmob", String.valueOf(list.size()));

                                }
                            }
                        });


                    }
                });


    }

    @Subscribe(sticky = true)
    public void onGetMessage(CarBeanHelper carBean) {
        String string = carBean.getName();
        getData("userName",string);
    }

    private void getData(String str,String string) {
        BmobQuery<CarBean> query = new BmobQuery<CarBean>();
        query.addWhereEqualTo(str, string);
        Log.e("updata","::run");
        query.findObjects( new FindListener<CarBean>() {
            @Override
            public void done(List<CarBean> list, BmobException e) {
                Log.e("newList",String.valueOf( list.size()));
                if (e == null) {
                    BigCarBean bigCarBean = new BigCarBean();
                    bigCarBean.setList(list);
                    mList.clear();
                    mList.add(bigCarBean);
                    mList.add(carBottomBeanMain);
                    shoppingFragmentAdapter.notifyDataSetChanged();
                }
            }
        });
    }
    private void upDataChoice(final boolean b, String name){
        final List<CarBean> newList=new ArrayList<CarBean>();
        final BigCarBean bigCarBean=new BigCarBean();
        BmobQuery<CarBean> query = new BmobQuery<CarBean>();
        Log.e("bmob", name);
        query.addWhereEqualTo("userName", name);
        query.findObjects(new FindListener<CarBean>() {
            @Override
            public void done(List<CarBean> list, BmobException e) {
                for(CarBean carBean:list){
                    carBean.setChoice( b);
                    newList.add(carBean);
                }
                bigCarBean.setList(newList);
                // mList.addAll(0, list);
                mList.clear();
                mList.add(bigCarBean);
                mList.add( carBottomBeanMain );
                shoppingFragmentAdapter.notifyDataSetChanged();

            }
        });
    }
}
